<?php

namespace Mapper;

/**
 * Queue
 */
class QueueModel extends \Mapper\Base\AbstractModel {
    use \Mapper\Base\InstanceModel;
    protected $table = 'queue';

    /**
     * 数据压入队列
     *
     * @param \QueueModel $queueModel
     * @return int
     */
    public function push(\QueueModel $queueModel){
        $queueModel->setTime(time());
        $queueModel->setStatus('pending');

        try {
            $lastId = $this->insert($queueModel);
        } catch (\Exception $ex) {
            $lastId = 0;
        }

        return $lastId;
    }

    /**
     * 拉取数据
     *
     * @return \QueueModel|null
     */
    public function pull($type){
        $queueModel = $this->fetch(array('type' => $type ,'status' => 'pending'), 'time ASC');

        if(!$queueModel instanceof \QueueModel){
            return null;
        }

        $queueModel->setStatus('processing');

        $this->begin();

        try {
            $effer = $this->update($queueModel);
        } catch (\Exception $ex) {
            $effer = 0;
        }

        if((int)$effer === 1){
            $this->commit();
            return $queueModel;
        }

        $this->rollback();
        return null;
    }
}